package com.luckynote.common.base.serialize;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * <pre>
 * *********************************************
 * Copyright LUCKY-NOTE.
 * All rights reserved.
 * ****************************************************
 *  Version       Date         Author            Desc
 *    v1.0       2019/6/29      bingo
 * ****************************************************
 * </pre>
 */
public class JDKSerializerUtil {

    private static final Logger logger = LoggerFactory.getLogger(JDKSerializerUtil.class);

    /**
     * 序列化对象，失败或异常返回null
     *
     * @param source 待序列化的目标对象
     * @return 已序列化的字节码
     */
    public static byte[] serialize(Object source) {
        byte[] result = null;
        ByteArrayOutputStream byteOS = null;
        ObjectOutputStream objectOS = null;

        try {
            byteOS = new ByteArrayOutputStream();
            objectOS = new ObjectOutputStream(byteOS);
            objectOS.writeObject(source);
            objectOS.flush();
            result = byteOS.toByteArray();
        } catch (IOException e) {
            logger.error("对象序列化失败", e);
        } finally {
            try {
                if (objectOS != null) {
                    objectOS.close();
                }
                if (byteOS != null) {
                    byteOS.close();
                }
            } catch (IOException e) {
                logger.error("对象序化流关闭失败", e);
            }
        }

        return result;
    }

    /**
     * 反序列化对象，失败或异常返回null
     *
     * @param source 已序列化的字节码
     * @param <T>    反序列化对象
     * @return 反序列化对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T deSerialize(byte[] source) {
        ByteArrayInputStream byteIS = null;
        ObjectInputStream objectIS = null;
        Object object = null;
        try {
            byteIS = new ByteArrayInputStream(source);
            objectIS = new ObjectInputStream(byteIS);
            object = objectIS.readObject();
        } catch (Exception e) {
            logger.error("对象反序列化失败", e);
        } finally {
            try {
                if (objectIS != null) {
                    objectIS.close();
                }
                if (byteIS != null) {
                    byteIS.close();
                }
            } catch (IOException e) {
                logger.error("对象序列化流关闭失败", e);
            }
        }
        return (T) object;
    }
}
